package com.woniuxy.store.service.consumer;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.store.infra.model.Function;
import com.woniuxy.store.infra.model.PackageFunction;
import com.woniuxy.store.infra.model.StoreContract;
import com.woniuxy.store.infra.model.StoreInfo;
import com.woniuxy.store.service.FunctionService;
import com.woniuxy.store.service.PackageFunctionService;
import com.woniuxy.store.service.StoreContractService;
import com.woniuxy.store.service.StoreInfoService;
import enums.RoleEnum;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@RocketMQMessageListener(consumerGroup = "package_pay",topic = "pay_checks")
@GlobalTransactional
public class PayCheckConsumer implements RocketMQListener<String> {


    @Resource
    private StoreContractService storeContractService;

    @Resource
    private StoreInfoService storeInfoService;

    @Resource
    private FunctionService functionService;

    @Resource
    private PackageFunctionService packageFunctionService;

    @Override
    public void onMessage(String num) {

        String result = storeContractService.payOrderCheck(num);
        StoreContract contract = storeContractService.getOne(new QueryWrapper<StoreContract>().eq("contract_num", num));
        if(result.equals("TRADE_SUCCESS")){
            contract.setPayState("PAID");
            storeContractService.updateById(contract);
            PackageFunction packageFunction = packageFunctionService.getById(contract.getPackageFunctionId());
            Function function = functionService.getById(packageFunction.getFunctionId());
            StoreInfo storeInfo = storeInfoService.getById(contract.getStoreId());
            storeInfo.setExpirationTime(contract.getExpirationTime());
            if (function.getFunctionName().equals("普通会员")){
                storeInfo.setStoreState(RoleEnum.ORDINARY.getMessage());
                storeInfo.setRoleId(RoleEnum.ORDINARY.getCode());
            }
            else {
                storeInfo.setStoreState(RoleEnum.PREMIUM.getMessage());
                storeInfo.setStoreId(RoleEnum.PREMIUM.getCode());
            }
            storeInfoService.updateById(storeInfo);
        }
        System.out.println(result);
    }
}
